package com.basker.pisces.core.query.builder;

import java.util.Arrays;
import java.util.List;

import com.basker.pisces.core.query.ICriteria;
import com.basker.pisces.core.query.criteria.CompositeCriterion;
import com.basker.pisces.core.query.criteria.Criterion;
import com.basker.pisces.core.query.meta.QueryMeta;
import com.google.common.collect.Lists;

class CriteriaBuilder extends CriterionBuilder {
    private int logicRelation = And;

    private List<CriterionBuilder> children;

    CriteriaBuilder(CriterionBuilder[] builders, int logicRelation) {
        this.children = Arrays.asList(builders);
        this.logicRelation = logicRelation;
    }

    CriteriaBuilder(List<CriterionBuilder> builders, int logicRelation) {
        this.children = Lists.newArrayList(builders);
        this.logicRelation = logicRelation;
    }

    @Override
    public Criterion createCriterion(QueryMeta queryMeta) {
        if (children.size() == 0) {
            return null;
        }

        CompositeCriterion criteria = new CompositeCriterion("");
        this.addChildren(queryMeta, criteria);

        return criteria.isEmpty() ? null : criteria;
    }

    public List<CriterionBuilder> getChildren() {
        return children;
    }

    public int getLogicRelation() {
        return logicRelation;
    }

    protected void addChildren(QueryMeta queryMeta, ICriteria criteria) {
        for (CriterionBuilder builder : children) {
            Criterion criterion = builder.createCriterion(queryMeta);
            if (criterion == null) {
                continue;
            }

            if (this.logicRelation == Or) {
                criterion.setAndOr(Criterion.OR);
            } else {
                criterion.setAndOr(Criterion.AND);
            }

            criteria.addCriterion(criterion);
        }
    }
}
